<template>
  <div>
    <!-- 文章头部 -->
    <q-card class="article-detail-card q-mb-xl" flat bordered>
      <q-img
        :src="article.image || 'https://source.unsplash.com/random/1200x600?blog'"
        :ratio="21/9"
        height="400px"
        class="article-header-image"
      >
        <div class="article-header-overlay flex flex-center column">
          <div class="text-center q-px-md">
            <div class="text-h3 text-white text-weight-bold">{{ article.title }}</div>
            <q-separator class="q-my-md bg-white" style="width: 80px; height: 3px; margin-left: auto; margin-right: auto; opacity: 0.7;" />
            <div class="text-subtitle1 text-white q-mt-sm">
              <q-badge outline color="white" class="q-mr-sm">
                <q-icon name="event" size="xs" class="q-mr-xs" /> {{ article.date }}
              </q-badge>
              <q-badge outline color="white">
                <q-icon name="folder" size="xs" class="q-mr-xs" /> {{ article.category }}
              </q-badge>
            </div>
          </div>
        </div>
      </q-img>

      <!-- 文章正文 -->
      <q-card-section class="q-py-lg">
        <div class="row q-mb-lg">
          <div class="col-12 article-tags">
            <q-chip 
              v-for="tag in article.tags" 
              :key="tag"
              outline
              color="primary"
              icon="tag"
              size="sm"
            >
              {{ tag }}
            </q-chip>
          </div>
        </div>

        <div class="article-content" v-html="article.content"></div>
      </q-card-section>

      <!-- 文章底部导航 -->
      <q-separator />
      <q-card-section>
        <div class="row justify-between items-center">
          <q-btn 
            v-if="article.prevArticle" 
            :to="`/articles/${article.prevArticle.id}`"
            color="primary" 
            flat 
            icon="arrow_back" 
            :label="article.prevArticle.title"
            class="navigation-btn"
          />
          <div v-else></div>

          <q-btn 
            v-if="article.nextArticle" 
            :to="`/articles/${article.nextArticle.id}`"
            color="primary" 
            flat 
            icon-right="arrow_forward" 
            :label="article.nextArticle.title"
            class="navigation-btn"
          />
          <div v-else></div>
        </div>
      </q-card-section>
    </q-card>

    <!-- 评论区 -->
    <q-card class="q-mb-xl comment-card" flat bordered>
      <q-card-section class="q-pb-none">
        <div class="text-h5 q-mb-md">
          <q-icon name="comment" color="primary" /> 评论 ({{ comments.length }})
        </div>
        <q-separator class="q-mb-md" />
      </q-card-section>

      <!-- 评论表单 -->
      <q-card-section class="q-pt-none">
        <div class="comment-form q-pa-md q-my-md bg-grey-1 rounded-borders">
          <div class="text-subtitle1 q-mb-sm text-weight-medium">发表评论</div>
          <q-input 
            v-model="newComment" 
            filled 
            type="textarea" 
            label="写下你的评论..." 
            rows="4"
            class="comment-input"
            :rules="[val => !!val || '请输入评论内容']"
            bg-color="white"
          />
          <div class="row justify-end q-mt-md">
            <q-btn 
              color="primary" 
              label="提交评论" 
              :loading="isSubmitting"
              :disable="!newComment.trim()"
              @click="submitComment"
            />
          </div>
        </div>

        <!-- 评论列表 -->
        <template v-if="comments.length > 0">
          <div class="q-mb-md comment-list">
            <q-list separator>
              <q-item v-for="comment in comments" :key="comment.id" class="q-py-md comment-item">
                <q-item-section avatar top>
                  <q-avatar color="primary" text-color="white">
                    {{ comment.author.charAt(0) }}
                  </q-avatar>
                </q-item-section>

                <q-item-section>
                  <q-item-label class="text-weight-bold">{{ comment.author }}</q-item-label>
                  <q-item-label caption class="text-grey-7">{{ comment.date }}</q-item-label>
                  <q-item-label class="q-mt-sm comment-content">{{ comment.content }}</q-item-label>
                </q-item-section>
              </q-item>
            </q-list>
          </div>
        </template>
        <template v-else>
          <div class="text-center q-pa-xl text-grey-6 bg-grey-1 rounded-borders">
            <q-icon name="forum" size="3rem" color="grey-5" />
            <div class="text-subtitle1 q-mt-md">暂无评论，快来发表第一条评论吧！</div>
          </div>
        </template>
      </q-card-section>
    </q-card>

    <!-- 相关文章 -->
    <q-card flat bordered class="related-articles-card">
      <q-card-section class="q-pb-none">
        <div class="text-h5 q-mb-md">
          <q-icon name="article" color="primary" /> 相关文章
        </div>
        <q-separator class="q-mb-md" />
      </q-card-section>

      <q-card-section class="q-pt-md">
        <div class="row q-col-gutter-md">
          <div class="col-12 col-md-4" v-for="relatedArticle in relatedArticles" :key="relatedArticle.id">
            <q-card bordered class="related-article-card" :to="`/articles/${relatedArticle.id}`" clickable>
              <q-img
                :src="relatedArticle.image || 'https://source.unsplash.com/random/800x450?blog'"
                :ratio="16/9"
                class="related-article-image"
              >
                <div class="absolute-full flex flex-center related-article-overlay">
                  <div class="text-subtitle1 text-weight-bold text-white text-center">
                    {{ relatedArticle.title }}
                  </div>
                </div>
              </q-img>
            </q-card>
          </div>
        </div>
      </q-card-section>
    </q-card>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'

const route = useRoute()
const router = useRouter()
const newComment = ref('')
const isSubmitting = ref(false)

// 文章数据
const article = ref({
  id: 1,
  title: 'Vue 3 组合式 API 实践指南',
  date: '2024-03-15',
  category: '技术分享',
  tags: ['Vue 3', 'JavaScript', '前端开发'],
  image: 'https://source.unsplash.com/random/1200x600?vue',
  content: `
    <h2>引言</h2>
    <p>Vue 3 的组合式 API 是一个革命性的特性，它为我们提供了更好的代码组织方式和逻辑复用能力。本文将深入探讨组合式 API 的核心概念、实际应用场景以及最佳实践，帮助您更好地理解和使用这一强大的特性。</p>
    
    <h2>组合式 API 基础</h2>
    <p>组合式 API 的核心是 setup 函数，它是组件中一个特殊的钩子函数，在组件实例创建之前执行。通过 setup 函数，我们可以使用一系列 API 函数来声明响应式状态、计算属性、监听器以及生命周期钩子。</p>

    <h3>响应式状态</h3>
    <p>使用 ref 和 reactive 函数来创建响应式状态：</p>
    <pre><code>
import { ref, reactive } from 'vue'

const count = ref(0)  // 基本类型使用 ref
const user = reactive({  // 对象类型使用 reactive
  name: 'Alice',
  age: 30
})
    </code></pre>

    <h3>计算属性和监听器</h3>
    <p>使用 computed 和 watch 函数来创建计算属性和监听器：</p>
    <pre><code>
import { computed, watch } from 'vue'

const doubleCount = computed(() => count.value * 2)

watch(count, (newValue, oldValue) => {
  console.log('count changed:', newValue, oldValue)
})
    </code></pre>
    
    <h2>生命周期钩子</h2>
    <p>在组合式 API 中，生命周期钩子变成了组合式函数，它们都以 "on" 开头：</p>
    <pre><code>
import { onMounted, onUpdated, onUnmounted } from 'vue'

onMounted(() => {
  console.log('Component is mounted!')
})
    </code></pre>
    
    <h2>逻辑复用</h2>
    <p>组合式 API 的一个主要优势是能够轻松地提取和复用逻辑。我们可以创建组合式函数（Composables）来封装和复用有状态逻辑：</p>
    <pre><code>
// useCounter.js
import { ref } from 'vue'

export function useCounter() {
  const count = ref(0)
  
  function increment() {
    count.value++
  }
  
  return {
    count,
    increment
  }
}

// 在组件中使用
import { useCounter } from './useCounter'

const { count, increment } = useCounter()
    </code></pre>
    
    <h2>与 Options API 对比</h2>
    <p>相比传统的 Options API，组合式 API 有以下优势：</p>
    <ul>
      <li>更好的代码组织：相关逻辑可以放在一起</li>
      <li>更好的逻辑复用：可以轻松提取和复用逻辑</li>
      <li>更好的类型推断：TypeScript 支持更好</li>
      <li>更小的包体积：通过摇树优化（tree-shaking）减小打包体积</li>
    </ul>
    
    <h2>最佳实践</h2>
    <p>在使用组合式 API 时，建议遵循以下最佳实践：</p>
    <ul>
      <li>使用有意义的函数命名：如 useCounter、useUser 等</li>
      <li>将复杂逻辑提取到组合式函数中</li>
      <li>使用 ref 存储基本类型，使用 reactive 存储对象类型</li>
      <li>避免过度解构 reactive 对象，这会失去响应性</li>
      <li>使用 toRefs 或 toRef 来保持解构的响应性</li>
    </ul>
    
    <h2>总结</h2>
    <p>Vue 3 的组合式 API 为我们提供了一种新的、更灵活的方式来组织和复用组件逻辑。通过本文的介绍，相信你已经对组合式 API 有了更深入的理解，可以在实际项目中更好地应用这一强大特性。</p>
  `,
  prevArticle: {
    id: 2,
    title: 'Quasar 框架开发体验'
  },
  nextArticle: null
})

// 评论数据
const comments = ref([
  {
    id: 1,
    author: '张三',
    date: '2024-03-16 15:30',
    content: '写得很好，对组合式 API 有了更深入的理解！期待更多相关内容。'
  },
  {
    id: 2,
    author: '李四',
    date: '2024-03-16 16:45',
    content: '文章讲解得很清晰，特别是关于逻辑复用的部分很有启发。'
  }
])

// 相关文章
const relatedArticles = ref([
  {
    id: 2,
    title: 'Quasar 框架开发体验',
    image: 'https://source.unsplash.com/random/800x450?ui'
  },
  {
    id: 5,
    title: '现代前端构建工具对比',
    image: 'https://source.unsplash.com/random/800x450?tools'
  },
  {
    id: 8,
    title: 'Vue 与 React 的对比分析',
    image: 'https://source.unsplash.com/random/800x450?framework'
  }
])

const submitComment = () => {
  if (!newComment.value.trim()) return
  
  isSubmitting.value = true
  
  // 模拟 API 请求延迟
  setTimeout(() => {
    // 添加新评论
    comments.value.unshift({
      id: Date.now(),
      author: '访客',
      date: new Date().toLocaleString(),
      content: newComment.value
    })
    
    // 重置表单和状态
    newComment.value = ''
    isSubmitting.value = false
  }, 800)
}

onMounted(() => {
  // 在实际应用中，这里可以根据 route.params.id 获取文章详情
  console.log('Article ID:', route.params.id)
  
  // 模拟根据 ID 获取文章详情
  // loadArticle(route.params.id)
})
</script>

<style scoped>
.article-detail-card {
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.comment-card,
.related-articles-card {
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.article-header-image {
  position: relative;
}

.article-header-overlay {
  background: linear-gradient(to bottom, rgba(0, 0, 0, 0.3), rgba(0, 0, 0, 0.7));
  position: absolute;
  width: 100%;
  height: 100%;
}

.article-content {
  line-height: 1.8;
  color: #333;
  font-size: 1.05rem;
  max-width: 800px;
  margin: 0 auto;
}

.article-content h2 {
  margin: 2em 0 1em;
  font-size: 1.8em;
  color: #222;
  font-weight: 600;
  border-bottom: 2px solid #f0f0f0;
  padding-bottom: 0.3em;
}

.article-content h3 {
  margin: 1.5em 0 0.8em;
  font-size: 1.5em;
  color: #333;
  font-weight: 500;
}

.article-content p {
  margin-bottom: 1.2em;
}

.article-content pre {
  background: #f8f8f8;
  padding: 1.2em;
  border-radius: 8px;
  overflow-x: auto;
  margin: 1.5em 0;
  border-left: 4px solid var(--q-primary);
}

.article-content code {
  font-family: 'Courier New', monospace;
  color: #444;
}

.article-content ul {
  margin: 1.2em 0;
  padding-left: 1.8em;
}

.article-content li {
  margin-bottom: 0.7em;
}

.navigation-btn {
  transition: transform 0.2s ease;
}

.navigation-btn:hover {
  transform: translateY(-2px);
}

.comment-form {
  transition: all 0.3s ease;
}

.comment-form:hover {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.comment-input {
  border-radius: 8px;
}

.comment-item {
  transition: background-color 0.3s ease;
}

.comment-item:hover {
  background-color: #f9f9f9;
}

.comment-content {
  line-height: 1.6;
}

.related-article-card {
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s ease;
  height: 100%;
}

.related-article-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.related-article-image {
  height: 100%;
}

.related-article-overlay {
  background: rgba(0, 0, 0, 0.5);
  transition: background 0.3s ease;
  padding: 1rem;
}

.related-article-card:hover .related-article-overlay {
  background: rgba(0, 0, 0, 0.7);
}
</style> 